import os
from turtle import pd

from testcases.amazon_auto_publish import evn
from testcases.amazon_auto_publish.api.common_api import api_detect_language, api_Infringement
from testcases.amazon_auto_publish.api.publish_es import api_query_es
from testcases.amazon_auto_publish.script.logger import ERROR, INFO, WARNING
from utils.mysqlUtils.con_mangodb import con_mangodb
from utils.mysqlUtils.db_utils import DB

# 生产环境,刊登+调价的生产
address1 = 'url1'
address2 = 'url2'
# mangodb1
address3 = 'url3'
# mangodb2
address4 = 'url4'
# 侵权禁售库
address5 = 'url5'
# 打标表
address6 = 'url6'


# 长度
class CaseLength:
    # 验证标题的长度
    def __init__(self, results, sku_id=None):
        if sku_id is None:
            sku_id = []
        self.title = []
        self.keywords = []
        self.description = []
        self.bullet_points1 = []
        self.bullet_points2 = []
        self.bullet_points3 = []
        self.bullet_points4 = []
        self.bullet_points5 = []
        self.site_code = []
        self.sku_id = []
        for i in range(len(results)):
            if len(results) == 0:
                print("此OrderSourceSKUID没有属性数据", sku_id[i])
            else:
                self.site_code.append(results[i]["SiteCode"])
                sku_id = results[i]["OrderSourceSKUID"]
                self.sku_id.append(sku_id)
                results_attributes = results[i]["TranslateAttributes"]
                for j in results_attributes:
                    if j["AttributeFieldName"] == "item_name":
                        self.title.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "bullet_point1":
                        self.bullet_points1.append(j["AttributeValue"])
                        # print(self.bullet_points1)
                    elif j["AttributeFieldName"] == "bullet_point2":
                        self.bullet_points2.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "bullet_point3":
                        self.bullet_points3.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "bullet_point4":
                        self.bullet_points4.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "bullet_point5":
                        self.bullet_points5.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "generic_keywords":
                        self.keywords.append(j["AttributeValue"])
                    elif j["AttributeFieldName"] == "product_description":
                        self.description.append(j["AttributeValue"])
                    else:
                        pass

    def length_title(self):
        for i in range(len(self.site_code)):
            if self.site_code[i] == "CA":
                if 50 <= len(self.title[i]) <= 100:
                    pass
                else:
                    INFO.logger.error(
                        f"OrderSourceSKUID为{self.sku_id[i]},标题长度为：{len(self.title[i])},不符合要求 {self.title[i]}")
                    # print("OrderSourceSKUID为%s,标题长度为：%s,不符合要求 %s" % (self.sku_id[i], len(self.title[i]), self.title[i]))
            if self.site_code[i] == "JP":
                if 50 <= len(self.title[i]) <= 90:
                    pass
                else:
                    INFO.logger.error(
                        f"OrderSourceSKUID为{self.sku_id[i]},标题长度为：{len(self.title[i])},不符合要求 {self.title[i]}")
                    # print("OrderSourceSKUID为%s,标题长度为：%s,不符合要求 %s" % (self.sku_id[i], len(self.title[i]), self.title[i]))

            else:
                if 50 <= len(self.title[i]) <= 180:
                    pass
                else:
                    INFO.logger.error(
                        f"OrderSourceSKUID为{self.sku_id[i]},标题长度为：{len(self.title[i])},不符合要求 {self.title[i]}")
                    # print("OrderSourceSKUID为%s,标题长度为：%s,不符合要求 %s" % (self.sku_id[i], len(self.title[i]), self.title[i]))

    def length_key_words(self):
        for i in range(len(self.keywords)):
            keywords = self.keywords[i].replace("\r\n", ",")
            if 200 <= len(keywords) <= 270:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}关键词长度的为：{len(keywords)}不符合要求{keywords}")

    def length_point(self):
        for i in range(len(self.bullet_points1)):
            if len(self.bullet_points1[i]) <= 500:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}亮点1长度的为：{len(self.bullet_points1[i])}不符合要求{self.bullet_points1[i]}")
        for i in range(len(self.bullet_points2)):
            if len(self.bullet_points2[i]) <= 500:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}亮点2长度的为：{len(self.bullet_points2[i])}不符合要求{self.bullet_points2[i]}")
        for i in range(len(self.bullet_points3)):
            if len(self.bullet_points3[i]) <= 500:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}亮点3长度的为：{len(self.bullet_points3[i])}不符合要求{self.bullet_points3[i]}")
        for i in range(len(self.bullet_points4)):
            if len(self.bullet_points4[i]) <= 500:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}亮点4长度的为：{len(self.bullet_points4[i])}不符合要求{self.bullet_points4[i]}")
        for i in range(len(self.bullet_points5)):
            if len(self.bullet_points5[i]) <= 500:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}亮点5长度的为：{len(self.bullet_points5[i])}不符合要求{self.bullet_points5[i]}")

    def length_descript(self):
        for i in range(len(self.description)):
            if len(self.description[i]) <= 1800:
                pass
            else:
                INFO.logger.error(
                    f"OrderSourceSKUID为{self.sku_id[i]}描述长度的为：{len(self.description[i])}不符合要求{self.description[i]}")

    def main_length(self):
        self.length_title()
        self.length_key_words()
        self.length_point()
        self.length_descript()


# 翻译
class CaseTranslate:
    def __init__(self, results, sku_id=None):
        if sku_id is None:
            sku_id = []
        self.title = []
        self.keywords = []
        self.description = []
        self.bullet_points = []
        self.site_code = []
        self.translate_data = []
        self.language = {'BR': 'pt', 'US': 'en', 'IT': 'it', 'DE': 'de', 'FR': 'fr', 'JP': 'ja', 'ES': 'es', 'PL': 'pl',
                         'NL': 'nl', 'SE': 'sv', 'MX': 'en',
                         'AE': 'en', 'TR': 'tr',
                         "GB": 'en', "CA": 'en', "AU": 'en', "IN": 'en', "SG": 'en', "SA": 'en', "BE": "nl"}
        for i in range(0, len(sku_id)):
            dict_translate_data = {}
            attributes_results = results[i]["TranslateAttributes"]
            # print(results[0]['Title'])
            if len(results) == 0:
                INFO.logger.error(
                    f"翻译验证：此OrderSourceSKUID没有数据{sku_id[i]}")
            else:
                dict_translate_data['SiteCode'] = str(results[i]['SiteCode'])
                dict_translate_data['OrderSourceSKU'] = results[i]['OrderSourceSKU']
                for j in attributes_results:
                    if j["AttributeFieldName"] in (
                            "item_name", "generic_keywords", "product_description", "bullet_point1", "bullet_point2",
                            "bullet_point3", "bullet_point4", "bullet_point5"):
                        dict_translate_data[j["AttributeFieldName"]] = j["AttributeValue"]
            self.translate_data.append(dict_translate_data)
        # print(self.translate_data)

    # 验证，调用翻译后的结果是否符合预期
    def verify_translate_data(self, detect_datas, expect_language, Attribute):
        # 获取翻译接口返回数据中的language
        try:
            for detect_data in detect_datas:
                if detect_data[0]:
                    if detect_data[1] == expect_language:
                        pass
                    else:
                        INFO.logger.error(
                            f"词{detect_data[0]},接口检测结果为{detect_data[1]}, 实际结果为：{expect_language} ")
                        INFO.logger.error(
                            f"OrderSourceSKU为{Attribute['OrderSourceSKU']}对应的站点为：{Attribute['SiteCode']} 有数据未翻译成对应的语言{self.language[Attribute['SiteCode']]}")
                        # print("接口检测结果为：%s" % detect_data["language"], "实际结果为：%s" % expect_language)
                        # print("OrderSourceSKUID为%s对应的站点为：%s有数据未翻译成对应的语言" % (i, self.translate_data[i][0]), detect_data["keyword"])
                else:
                    pass
        except Exception as e:
            print(e, "调用翻译接口，接口返回数据异常")

    # 验证标题的翻译结果
    def translate(self):
        for Attribute in self.translate_data:
            # 验证标题和五个亮点
            wait_detected_data1 = [Attribute["item_name"], Attribute["bullet_point1"], Attribute["bullet_point2"],
                                   Attribute["bullet_point3"], Attribute["bullet_point4"], Attribute["bullet_point5"]]
            # 预期结果
            expect_language = self.language[Attribute['SiteCode']]
            # 调用翻译判断接口
            api_data1 = api_detect_language(wait_detected_data1, self.language[Attribute['SiteCode']])
            # 验证是否符合预期
            self.verify_translate_data(api_data1, expect_language, Attribute)
            # 待验证关键词
            wait_detected_generic_keywords = Attribute["generic_keywords"].split("\r\n")
            # 验证是否符合预期
            api_data2 = api_detect_language(wait_detected_generic_keywords, self.language[Attribute['SiteCode']])
            self.verify_translate_data(api_data2, expect_language, Attribute)
            # 待验证的描述
            '''
            wait_detected_product_description = Attribute["product_description"].replace("</b><br />", "\\1\\").replace("<br /><br /><b>", "\\1\\").replace("<br />", "\\1\\").replace(
                "<b>", "\\1\\")
            wait_detected_product_description=wait_detected_product_description.split("\\1\\")

            wait_detected_product_description=Attribute["product_description"].replace("</b><br />", ",").replace("<br /><br /><b>", ",").replace("<br />", ",").replace(
                "<b>", ",")
            #wait_detected_product_description=list(wait_detected_product_description)
            # 验证是否符合预期
            api_data3 = api_detect_language(wait_detected_product_description,self.language[Attribute['SiteCode']])
            self.verify_translate_data(api_data3,expect_language,Attribute)'''


# 去重
class CaseCompareRepetition:
    def __init__(self, sku_id, wait_verify_results):
        # 查询各站点的数据
        self.sku_sitecode_skuid_MarkListing = {}

        self.sku_sitecode_AmazonListingInfos = {}

        self.AmazonListingInfo_appoint_fields = {"OrderSourceID": 1, "OrderSourceSKU": 1, "OrderSourceSKUID": 1,
                                                 "Title": 1, "Generickeywords": 1, "Description": 1, "BulletPoints": 1}
        self.MarkListing_appoint_fields = {"OrderSourceId": 1, "OrderSourceSKU": 1, "ASIN": 1, "SiteCode": 1,
                                           "ListingStatus": 1,
                                           "SKU": 1, "OrderSourceSKUID": 1, "IsFBA": 1, "IsBrotherFBA": 1,
                                           "OnShelfMode": 1}
        self.country_data = {"US": [], "AE": [], "AU": [], "BR": [], "CA": [], "DE": [], "ES": [], "FR": [],
                             "GB": [],
                             "IN": [],
                             "IT": [], "JP": [], "MX": [], "NL": [], "PL": [], "SA": [], "SE": [],
                             "SG": [], "TR": [],
                             "BE": []}

        # 把sku分组到各站点
        for wait_verify_result in wait_verify_results:
            AutoPublishUploadProductQueueNew_SiteCode = wait_verify_result["SiteCode"]
            AutoPublishUploadProductQueueNew_SKU = wait_verify_result["SKU"]

            if AutoPublishUploadProductQueueNew_SiteCode in ["US", "CA"]:
                self.country_data["US"].append(AutoPublishUploadProductQueueNew_SKU)
                self.country_data["CA"].append(AutoPublishUploadProductQueueNew_SKU)

            else:
                self.country_data[AutoPublishUploadProductQueueNew_SiteCode].append(
                    AutoPublishUploadProductQueueNew_SKU)
        # skuid按照站点分组查询打标表，找到sku对应所有skuid,
        '''for key, value in self.country_data.items():
            MarkListing_table_name = "MarkListing_%s" % (key)
            if value:
                MarkListing_datas = con_mangodb("Amazon_MarkListing", MarkListing_table_name, 2, address6, self.MarkListing_appoint_fields,
                                                    SKU={"$in": value})
                self.sku_skuid_MarkListings = []
            # 按照sku+站点分组skuid
                for MarkListing_data in MarkListing_datas:
                    MarkListing_sku=MarkListing_data["SKU"]
                    MarkListing_OrderSourceSKUID=MarkListing_data["OrderSourceSKUID"]
                    MarkListing_SiteCode=MarkListing_data["SiteCode"]
                    self.sku_skuid_MarkListings.append(MarkListing_OrderSourceSKUID)
                    self.sku_sitecode_skuid_MarkListing[MarkListing_sku+"_"+MarkListing_SiteCode]=self.sku_skuid_MarkListings
                    '''
        # 在AmazonListingInfo把同站点所有数据查询出来
        for key, value in self.country_data.items():
            if value:
                AmazonListingInfo_table_name = "AmazonListingInfo_%s" % (key)
                AmazonListingInfo_datas = con_mangodb("Amazon_AutoPublish", AmazonListingInfo_table_name, 2, address6,
                                                      self.AmazonListingInfo_appoint_fields,
                                                      SKU={"$in": value})
                try:
                    for AmazonListingInfo_data in AmazonListingInfo_datas:
                        AmazonListingInfo_sku = AmazonListingInfo_data["SKU"]
                        AmazonListingInfo_OrderSourceSKUID = AmazonListingInfo_data["OrderSourceSKUID"]
                        AmazonListingInfo_SiteCode = AmazonListingInfo_data["SiteCode"]
                        AmazonListingInfo_BulletPoints = AmazonListingInfo_data["BulletPoints"]
                        AmazonListingInfo_Description = AmazonListingInfo_data["Description"]
                        if AmazonListingInfo_data["Generickeywords"]:
                            AmazonListingInfo_Generickeywords = AmazonListingInfo_data["Generickeywords"].split("\n")
                        AmazonListingInfo_Title = AmazonListingInfo_data["Title"]
                        sku_sitecode = AmazonListingInfo_sku + "_" + AmazonListingInfo_SiteCode
                        if self.sku_sitecode_AmazonListingInfos.keys() and sku_sitecode in self.sku_sitecode_AmazonListingInfos.keys():
                            self.sku_sitecode_AmazonListingInfos[sku_sitecode]["Title"].append(AmazonListingInfo_Title)
                            self.sku_sitecode_AmazonListingInfos[sku_sitecode]["Generickeywords"].extend(
                                AmazonListingInfo_Generickeywords)
                            self.sku_sitecode_AmazonListingInfos[sku_sitecode]["BulletPoints"].extend(
                                AmazonListingInfo_BulletPoints)
                            self.sku_sitecode_AmazonListingInfos[sku_sitecode]["Description"].append(
                                AmazonListingInfo_Description)
                        else:
                            self.sku_sitecode_AmazonListingInfos[sku_sitecode] = {"Title": [AmazonListingInfo_Title],
                                                                                  "Generickeywords": AmazonListingInfo_Generickeywords,
                                                                                  "Description": [
                                                                                      AmazonListingInfo_Description],
                                                                                  "BulletPoints": AmazonListingInfo_BulletPoints}
                except Exception as e:
                    print(e)
            else:
                pass
        print(self.sku_sitecode_AmazonListingInfos)

    def find_repeated_words(self, text1, text2, length):
        # 从text1每次取50个字符，要取多少次,到最后不足length的长度，就不用取了
        y = len(text1) - 2 - length
        for j in range(0, y):
            Continuous_words_length = length + j + 1
            # 取连续的50个词
            new_data = text1[j:Continuous_words_length]
            if new_data in text2:
                return new_data
            else:
                pass

    def compare_title(self, key,Titles, length=50):
        '''length:多少字符算重复'''
        Titles_length = len(Titles)
        try:
            for index, value in enumerate(Titles):
                sku_wait_verify_Title = value
                # 拿取到的数据和这个数据后面的数据进行比较
                for i in range(index + 1, Titles_length):
                    sku_other_Title = Titles[i]
                    repeated_words_length = self.find_repeated_words(sku_wait_verify_Title, sku_other_Title,
                                                                     length)
                    if repeated_words_length:
                        INFO.logger.error(
                            f"重复Title:{key},待验证的数据：{sku_wait_verify_Title}, 参照数据{sku_other_Title}")
                    else:
                        pass
        except Exception as e:
            print(key,"属性表存在Title为空的数据",e)

    def compare_description(self, key,descriptions, length=300):
        '''length:多少字符算重复'''
        descriptions_length = len(descriptions)
        try:
            for index, value in enumerate(descriptions):
                sku_wait_verify_descriptions = value
                # 拿取到的数据和这个数据后面的数据进行比较
                for i in range(index + 1, descriptions_length):
                    sku_other_descriptions = descriptions[i]
                    repeated_words_length = self.find_repeated_words(sku_wait_verify_descriptions,
                                                                     sku_other_descriptions,
                                                                     length)
                    if repeated_words_length:
                        INFO.logger.error(
                            f"重复描述:{key},待验证的数据：{sku_wait_verify_descriptions}, 参照数据{sku_other_descriptions}")
                    else:
                        pass
        except Exception as e:
            print(key,"属性表存在描述为空的数据",e)

    def compare_bullet_point(self,key, points):
        points_length = len(points)
        try:
            for index, value in enumerate(points):
                sku_wait_verify_points = value
                # 拿取到的数据和这个数据后面的数据进行比较
                for i in range(index + 1, points_length):
                    sku_other_points = points[i]
                    if sku_wait_verify_points in sku_other_points:
                        INFO.logger.error(
                        f"重复亮点:{key},待验证的数据：{sku_wait_verify_points}, 参照数据{sku_other_points}")
                    else:
                        pass
        except Exception as e:
            print(key,"属性表存在亮点为空的数据",e)

    def compare_keyword(self, key,keywords):
        try:
            for keyword in keywords:
                sku_other_keyword = keywords.remove(keyword)
                if keyword in sku_other_keyword:
                    INFO.logger.error(
                        f"重复关键词:{key},待验证的数据：{keyword}, 参照数据{sku_other_keyword}")
                else:
                    pass
        except Exception as e:
            print(key,"属性表存在关键词为空的数据",e)

    def main_compare_repetition(self):
        for key, value in self.sku_sitecode_AmazonListingInfos.items():
            Titles = value["Title"]
            self.compare_title(key,Titles)
            descriptions = value["Description"]
            self.compare_description(key,descriptions)
            points = value["BulletPoints"]
            self.compare_bullet_point(key,points)
            keywords = value["Generickeywords"]
            self.compare_keyword(key,keywords)


# 敏感词
class CaseSensitiveWords():
    def __init__(self, results, sku_id=None):
        self.skuid = []
        self.title = []
        self.keywords = []
        self.description = []
        self.bullet_points1 = []
        self.bullet_points2 = []
        self.bullet_points3 = []
        self.bullet_points4 = []
        self.bullet_points5 = []
        self.site_code = []
        self.title_version = []
        self.results = results
        # 查出所有数据，输出格式 self.title=[（skuid,sitecode,title）,（skuid,sitecode,title）]
        if len(results) > 0:
            for result in results:
                Attributes = result["TranslateAttributes"]
                self.skuid.append(result["OrderSourceSKUID"])
                for Attribute in Attributes:
                    if Attribute["AttributeFieldName"] == "item_name":
                        item_name = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point1":
                        bullet_point1 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point2":
                        bullet_point2 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point3":
                        bullet_point3 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point4":
                        bullet_point4 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point5":
                        bullet_point5 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "generic_keywords":
                        generic_keywords = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "product_description":
                        product_description = Attribute["AttributeValue"]
                    else:
                        pass
                title_data = (result["OrderSourceSKUID"], result["SiteCode"], item_name)
                self.title.append(title_data)

                generic_keywords = (
                    result["OrderSourceSKUID"], result["SiteCode"], generic_keywords, result["TitleVersion"])
                self.keywords.append(generic_keywords)

                product_description = (result["OrderSourceSKUID"], result["SiteCode"], product_description)
                self.description.append(product_description)

                bullet_point1 = (result["OrderSourceSKUID"], result["SiteCode"], bullet_point1)
                self.bullet_points1.append(bullet_point1)

                bullet_point2 = (result["OrderSourceSKUID"], result["SiteCode"], bullet_point2)
                self.bullet_points2.append(bullet_point2)

                bullet_point3 = (result["OrderSourceSKUID"], result["SiteCode"], bullet_point3)
                self.bullet_points3.append(bullet_point3)

                bullet_point4 = (result["OrderSourceSKUID"], result["SiteCode"], bullet_point4)
                self.bullet_points4.append(bullet_point4)

                bullet_point5 = (result["OrderSourceSKUID"], result["SiteCode"], bullet_point5)
                self.bullet_points5.append(bullet_point5)
        else:
            print("此OrderSourceSKUID没有Attributes数据", sku_id)
        # print("self.title",self.title)

    def get_senstive_words(self):

        senstive_words_results = con_mangodb("zhcxkj_amazon", "AutoPublishWordFilterMgoModel", 2, address3)
        country_data = {"US": [], "AE": [], "AU": [], "BR": [], "CA": [], "DE": [], "ES": [], "FR": [], "GB": [],
                        "IN": [],
                        "IT": [], "JP": [], "MX": [], "NL": [], "PL": [""], "SA": [], "SE": [],
                        "SG": [], "TR": [],
                        "BE": []}

        lenth = len(senstive_words_results)
        for i in range(0, lenth):
            Keyword = senstive_words_results[i]["Keyword"].lower()
            for j in (senstive_words_results[i]["SiteCodes"]):
                SiteCode = j
                country_data[SiteCode].append(Keyword)
        print("所有敏感词", country_data)
        return country_data

    def verify_senstive_title(self, senstive_sitecodes):
        '''
        senstive_sitecodes:站点对应的所有敏感词
        skuids：ordersouceskuid'''
        for i in range(0, len(self.results)):
            skuid = self.title[i][0]
            # 待验证的标题的国家
            sitecode = self.title[i][1]
            # 待验证的标题
            title = self.title[i][2].lower()
            senstive_sitecode = senstive_sitecodes[sitecode]
            for senstive in senstive_sitecode:
                if senstive in title:
                    print("标题有敏感词", skuid, senstive)
                else:
                    pass

    def verify_senstive_key_word(self, senstive_sitecodes):
        for i in range(0, len(self.results)):
            skuid = self.keywords[i][0]
            # 待验证的关键词的国家
            sitecode = self.keywords[i][1]
            # 待验证的关键词的标题版本
            titleversion = self.keywords[i][3]
            # 待验证的关键词
            key_words = self.keywords[i][2].lower()
            # key_words = key_words.split("\n\n\n")
            key_words = key_words.split("\r\n")
            senstive_sitecode = senstive_sitecodes[sitecode]
            # 增加默认词
            special_word = ["that", "be", "been", "being", "a", "an", "the", "and", "or", "as", "of", "at", "by",
                            "for", "with"]
            senstive_sitecode_key_words = senstive_sitecode + special_word
            for key_word in key_words:
                if titleversion == "FBA":
                    # 把关键词拆成词根，以列表形式输出
                    key_word = key_word.split()
                    find_senstive_data = [x for x in senstive_sitecode_key_words if x in key_word]
                    if len(find_senstive_data) > 0:
                        print("关键词有敏感词", skuid, find_senstive_data)
                else:
                    find_senstive_data2 = [x for x in key_words if x in senstive_sitecode_key_words]
                    if len(find_senstive_data2) > 0:
                        print("关键词有敏感词", skuid, find_senstive_data2)

    def verify_senstive_description(self, senstive_sitecodes):
        for i in range(0, len(self.results)):
            skuid = self.description[i][0]
            # 待验证的标题的国家
            sitecode = self.description[i][1]
            # 待验证的描述
            descript_data = self.description[i][2].lower()

            senstive_sitecode = senstive_sitecodes[sitecode]
            for senstive in senstive_sitecode:
                if senstive in descript_data:
                    print("descript_data有敏感词", skuid, senstive)
                else:
                    pass

    def verify_senstive_point(self, senstive_sitecodes):
        for i in range(0, len(self.results)):
            skuid = self.bullet_points1[i][0]
            # 待验证的标题的国家
            sitecode = self.bullet_points1[i][1]
            # 待验证的亮点1
            point1 = str(self.bullet_points1[i][2]).lower()
            # 待验证的亮点2
            point2 = str(self.bullet_points2[i][2]).lower()
            # 待验证的亮点3
            point3 = str(self.bullet_points3[i][2]).lower()
            # 待验证的亮点4
            point4 = str(self.bullet_points4[i][2]).lower()
            # 待验证的亮点5
            point5 = str(self.bullet_points5[i][2]).lower()
            senstive_sitecode = senstive_sitecodes[sitecode]
            for senstive in senstive_sitecode:
                if senstive in point1:
                    print("point1有敏感词", skuid, senstive)
                elif senstive in point2:
                    print("point2有敏感词", skuid, senstive)
                elif senstive in point3:
                    print("point3有敏感词", skuid, senstive)
                elif senstive in point4:
                    print("point4有敏感词", skuid, senstive)
                elif senstive in point5:
                    print("point5有敏感词", skuid, senstive)
                else:
                    pass

    def main_verify_senstive(self):
        skuids = self.skuid
        # 站点对应的敏感词
        senstive_sitecodes = self.get_senstive_words()
        self.verify_senstive_title(senstive_sitecodes)
        self.verify_senstive_key_word(senstive_sitecodes)
        self.verify_senstive_description(senstive_sitecodes)
        self.verify_senstive_point(senstive_sitecodes)


# 侵权验证
class CaseInfringement():
    def __init__(self, results, sku_id=None):
        if sku_id is None:
            sku_id = []
        self.Infringement_datas = []
        self.skuid = sku_id
        self.queueids = []
        # 查出所有数据，输出格式 [{skuid,sitecode,CategoryPathId,keyWords,queueid},{skuid,sitecode,CategoryPathId,keyWords}]
        if len(results) > 0:
            for result in results:
                Attributes = result["TranslateAttributes"]
                QueueID = int(result["QueueID"])
                self.queueids.append(QueueID)
                for Attribute in Attributes:
                    if Attribute["AttributeFieldName"] == "item_name":
                        item_name = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point1":
                        bullet_point1 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point2":
                        bullet_point2 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point3":
                        bullet_point3 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point4":
                        bullet_point4 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "bullet_point5":
                        bullet_point5 = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "generic_keywords":
                        generic_keywords = Attribute["AttributeValue"]
                    if Attribute["AttributeFieldName"] == "product_description":
                        product_description = Attribute["AttributeValue"]
                    else:
                        pass
                keyWords = [item_name, bullet_point1, bullet_point2, bullet_point3, bullet_point4, bullet_point5,
                            generic_keywords, product_description]
                CategoryPathId = None
                Infringement_data = {"OrderSourceSKUID": result["OrderSourceSKUID"], "SiteCode": result["SiteCode"],
                                     "CategoryPathId": CategoryPathId, "keyWords": keyWords, "QueueID": QueueID}
                self.Infringement_datas.append(Infringement_data)
        else:
            print("此OrderSourceSKUID没有Attributes数据", sku_id)

        # print("Infringement_datas", self.Infringement_datas)

    def verify_Infringement(self):
        # 查询所有的类目id
        Auto_Publish_UploadResultQueue_results = con_mangodb("Amazon_AutoPublish", "AutoPublishUploadResultQueue", 2,
                                                             address1,
                                                             QueueID={"$in": self.queueids})
        # 查把类目id赋值至对应的skuid中,
        for Auto_Publish_UploadResultQueue_result in Auto_Publish_UploadResultQueue_results:
            BrowsePathByID = Auto_Publish_UploadResultQueue_result["BrowsePathByID"]
            Auto_Publish_UploadResultQueue_QueueID = Auto_Publish_UploadResultQueue_result["QueueID"]
            for Infringement_data in self.Infringement_datas:
                if Infringement_data["QueueID"] == Auto_Publish_UploadResultQueue_QueueID:
                    Infringement_data["CategoryPathId"] = BrowsePathByID
                else:
                    pass
        # 然后调用接口验证是否有侵权词
        for Infringement_data in self.Infringement_datas:
            siteCode = Infringement_data["SiteCode"]
            CategoryPathId = Infringement_data["CategoryPathId"]
            keyWords = Infringement_data["keyWords"]
            api_datas = api_Infringement(siteCode, CategoryPathId, keyWords)
            try:
                for api_data in api_datas:
                    if len(api_data["SensitiveWords"]) > 0 or len(api_data["BrandWords"]) > 0 or len(
                            api_data["ProductBrands"]) > 0:
                        print("有侵权词，调用侵权词接口验证结果", api_data)
                else:
                    pass
            except Exception as e:
                print(e)


# 继承父类，重写__init__
class GetPublishData(CaseLength):
    def __init__(self):
        data = pd.read_excel('fba的测试数据.xlsx')
        # 以列表形式输出指定列数据
        self.title = data["标题"].tolist()
        self.keywords = data["关键词"].tolist()
        self.description = data["描述"].tolist()
        self.bullet_points1 = data["亮点1"].tolist()
        self.bullet_points2 = data["亮点2"].tolist()
        self.bullet_points3 = data["亮点3"].tolist()
        self.bullet_points4 = data["亮点4"].tolist()
        self.bullet_points5 = data["亮点5"].tolist()
        self.site_code = data["sitecode"].tolist()
        self.sku_id = data["sku"].tolist()


def main_publish():
    # es_data = api_query_es()
    skuids = []
    # 指定数据验证
    skuids = [
        4661401335, 4659496878
    ]
    print("验证的litingid", skuids)
    # 上架队列
    results = con_mangodb("Amazon_AutoPublish", "AutoPublishUploadProductQueueNew", 2, address1,
                          OrderSourceSKUID={"$in": skuids})

    # 侵权
    # CaseInfringement(results, skuids).verify_Infringement()
    # 验证标题长度# 关键词长度# 亮点长度# 描述长度
    # CaseLength(results, skuids).main_length()
    # 敏感词标题验证# 敏感词关键词验证 # 敏感词描述验证# 敏感词亮点验证
    # CaseSensitiveWords(results, skuids).main_verify_senstive()
    # 验证是否翻译，未翻译成对应语言会输出
    # CaseTranslate(results, skuids).translate()
    # 验证资料是否重复
    CaseCompareRepetition(skuids, results).main_compare_repetition()


if __name__ == '__main__':
    main_publish()
